<template>
	<div class="index">
        <div :class="{blur:blurBtn}" style="height:100%;">
            <div class="title">今日点单数</div>
            <div class="orderNumber" v-text="orderCount"></div>
    		<div class="menuBox clearfix">
                <router-link to="/takeOrder" tag="div" class="item color1">
                    <i class="iconfont icon-diancantianchong"></i>
                    <div class="name">点单</div>
                </router-link>
                <!--  -->
                <router-link to="/region" v-if="showRegion" tag="div" class="item color1">
                    <i class="iconfont icon-diannao"></i>
                    <div class="name">机位</div>
                </router-link>
                <!--  -->
                <router-link to="/order" tag="div" class="item color2">
                    <i class="iconfont icon-dingdan"></i>
                    <div class="name">订单</div>
                </router-link>
                <router-link v-if="makeEnabled==1" to="/sendOrder" tag="div" class="item color2">
                    <i class="iconfont icon-dingdan"></i>
                    <div class="name">配送单</div>
                </router-link>
                <router-link class="item color3" to="/achievement" tag="div">
                    <i class="iconfont icon-yejiguanli"></i>
                    <div class="name">业绩</div>
                </router-link>
                <router-link class="item color5" to="/earnings" tag="div">
                    <i class="iconfont icon-money"></i>
                    <div class="name">收益</div>
                </router-link>
                <div class="item color4" @click="getQrcode">
                    <i class="iconfont icon-huiyuan"></i>
                    <div class="name">会员</div>
                </div>
                <!-- <router-link class="item color6" to="/coupon" tag="div">
                    <i class="iconfont icon-youhuiquan"></i>
                    <div class="name">优惠券</div>
                </router-link> -->
                <router-link class="item color7" to="/check" tag="div">
                    <i class="iconfont icon-pandian"></i>
                    <div class="name">盘点</div>
                </router-link>
                <router-link class="item color8" to="/waitSite" tag="div">
                    <i class="iconfont icon-shijian"></i>
                    <div class="name">排号</div>
                </router-link>
                <router-link v-if="makeEnabled!=1" class="item color8" to="/workshift" tag="div">
                    <i class="iconfont icon-workclock"></i>
                    <div class="name">交班记录</div>
                </router-link>
                <router-link class="item color8" to="/reward" tag="div">
                    <i class="iconfont icon-workclock"></i>
                    <div class="name">打赏记录</div>
                </router-link>
                <div class="item color8" @click.stop="doShowMoreMenu">
                    <i class="iconfont icon-gengduo"></i>
                    <div class="name">更多</div>
                </div>
                <div class="item color9" @click="logout">
                    <i class="iconfont icon-tuichudenglu"></i>
                    <div class="name">退出</div>
                </div>
                
            </div>
        </div>
        <div class="code" v-if="isqrcode" @click="isqrcode=false;blurBtn=false;">
            <div class="form-wrap" @click.stop="">
                <div class="tit">方式一：</div>
                <div class="form-item">
                    <div class="form-name">*手机号</div>
                    <div class="item-cont">
                        <input type="tel" v-model="vipForm.mobile" placeholder="请输入手机号"/>
                    </div>
                </div>
                <div class="form-item">
                    <div class="form-name">姓名</div>
                    <div class="item-cont">
                        <input type="text" v-model="vipForm.name" placeholder="请输入姓名"/>
                    </div>
                </div>
                <!-- <div class="form-item">
                    <div class="form-name">*验证码</div>
                    <div class="item-cont">
                        <input type="text" v-model="vipForm.code" style="padding-right:2rem" placeholder="请输入验证码"/>
                        <span class="get-code" @click.stop="getCode">{{codeInfo}}</span>
                    </div>
                </div> -->
                <button class="sub-btn" @click.stop="submitVip">确定</button>
            </div>
            <div class="tit2">方式二：</div>
            <div id="qrcode" @click.stop=""></div>
            <div class="tip">微信扫码并关注“火星捕手”即可成为会员</div>
            <div class="vip-charge" @click.stop="showVipInpFun">会员充值</div>
        </div>

        <!--  -->
        <div class="vip-inp" v-if="showVipInp" @click="showVipInp=false;">
            <div class="inp-box">
                <div class="inp-wrap">
                    <input type="text" @click.stop="" v-model="EnterPhone" placeholder="请输入会员账号,至少4位"/>
                    <div class="vip-list" @click.stop="" v-if="vipPhoneList&&vipPhoneList.length">
                        <ul>
                            <li v-for="(item,index) in vipPhoneList" :key="index" @click="selPhoneVip(item)">
                                <span class="vip-name left">{{item.name}}</span>
                                <span class="vip-num right">{{item.mobile}}</span>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="recharge" v-if="showRecharge">
            <div class="recharge-box" :style="showChargeType?'height:auto;padding:.2rem 0;':''">
                <div class="recharge-tit">会员充值</div>
                <div class="vip-info">
                    <span class="name">会员名称:{{vipData.name}}</span>
                    <span class="count-info right">会员账号:{{vipData.mobile}}</span>
                </div>
                <div class="customize-money" v-if="!showChargeType">
                    <span>自定义金额：</span>
                    <input type="text" v-model="inputVipMoney" name="" id="" placeholder="充值金额" />
                </div>
                <span v-if="!showChargeType">
                    <!-- this.$createScroll('scroll_store'); -->
                    <div class="recharge-rules" id="recharge">
                        <ul>
                            <li v-for="(item,index) in chargeRules" :key="index" @click="chargeVip(item)">{{item.name}}</li>
                        </ul>
                    </div>
                    <div class="confirm-box">
                        <button @click="showRecharge=false">取消</button>
                        <button class="yes" @click="chargeVip(null)">确定</button>
                    </div>
                </span>
                <div class="money-info" v-if="showChargeType">
                    <div class="money-info-box">
                        <div class="back">
                            <span @click="showChargeType=false">返回</span>
                        </div>
                        <span class="amount">￥{{curVipChargeInfo.amount}}</span>
                        <div class="charge-code">流水号：{{curVipChargeInfo.code}}</div>
                    </div>
                    <div class="pay">
                        <button @click="chargePay">在线支付</button>
                    </div>
                </div>
            </div>
        </div>
        <!--  -->
        <div class="more-menu-mask" v-if="showMoreMenu" @click.stop="doShowMoreMenu">
            <div class="more-menu-wrap" @click.stop="">
                <div class="more-menu-item">
                    <router-link class="menu-inner-wrap" to="/coupon" tag="div">
                        <span>
                            <div class="menu-icon iconfont icon-youhuiquan"></div>
                            <div class="menu-name">优惠券</div>
                        </span>
                    </router-link>
                </div>
                <div class="more-menu-item">
                    <router-link class="menu-inner-wrap" to="/rentOrder" tag="div">
                        <span>
                        <div class="menu-icon iconfont icon-zulin1"></div>
                        <div class="menu-name">外设换机</div>
                        </span>
                    </router-link>
                </div>
                <!-- <div class="more-menu-item" v-if="leaseEnabled"> -->
                    <div class="more-menu-item">
                    <router-link class="menu-inner-wrap" to="/returnRent" tag="div">
                        <span style="padding-top: 0px;">
                        <div style="font-size:.55rem;" class="menu-icon iconfont icon-guihuan"></div>
                        <div class="menu-name" style="margin-top: 0px;">外设归还</div>
                        </span>
                    </router-link>
                </div>
                <div class="more-menu-item">
                    <router-link class="menu-inner-wrap" to="/bigScreen" tag="div">
                        <span>
                        <div class="menu-icon iconfont icon-online"></div>
                        <div class="menu-name">机位大屏</div>
                        </span>
                    </router-link>
                </div>
                <div class="more-menu-item" v-if="showSelStore">
                    <router-link class="menu-inner-wrap" to="/selStore" tag="div">
                        <span>
                        <div class="menu-icon iconfont icon-qiehuan" style="font-size: .59rem;"></div>
                        <div class="menu-name">切换店铺</div>
                        </span>
                    </router-link>
                </div>
            </div>
        </div>
	</div>
</template>

<script>
import {API_BASE_URL} from "./../../urlConfig/index";
export default {
  	data(){
  		return{
            showSelStore:false,
            showMoreMenu:false,
            makeEnabled:-1,
            showRegion:false,
            codeInfo:"获取验证码",
            vipForm:{
                name:"",
                code:"",
                mobile:""
            },
            // 
            showChargeType:false,
            curVipChargeInfo:{},
            inputVipMoney:"",
            isqrcode:false,
            htmlCodeBtn:false,
            orderCount: 0, // 今日订单数量
            blurBtn:false,
            storeId: '',
            showRecharge:false,
            showVipInp:false,
            vipPhoneList:[],
            EnterPhone:"",
            vipData:{},
            chargeRules:[],//充值规则
            payCode:'',
            canClick:true,
            leaseEnabled:false,
  		}
      },
      watch: {
        EnterPhone ( val ) {
            if ( !(val.replace(/\s/g,'')) ) {
                this.vipPhoneList = [];
                return;
            }
            if(val.length<4){
                return;
            }
            this.$http.get(API_BASE_URL+'v1/member/members-search?storeId='+this.storeId+'&q='+val).then((res)=>{
                for (var i = 0; i < res.data.length; i++) {
                    res.data[i].amount = res.data[i].amount.toFixed(2);
                }
                this.vipPhoneList = res.data;
            })
        },
        isqrcode(val){
            if(!val){
                this.vipForm = {
                    name:"",
                    code:"",
                    mobile:""
                }
            }
        }
    },
    methods:{
        doShowMoreMenu(){
            this.showMoreMenu = !this.showMoreMenu;
            this.blurBtn = !this.blurBtn;
        },
        // 
        submitVip(){
            if(!String(this.vipForm.mobile).trim()){
                this.$message({
                    message: '请输入手机号',
                    customClass: 'error'
                });
                return;
            }
            // if(!String(this.vipForm.name).trim()){
            //     this.$message({
            //         message: '请输入姓名',
            //         customClass: 'error'
            //     });
            //     return;
            // }
            // if(!String(this.vipForm.code).trim()){
            //     this.$message({
            //         message: '请输入验证码',
            //         customClass: 'error'
            //     });
            //     return;
            // }
            if(!this.canClick){
                return;
            }
            this.canClick = false;
            this.$http({
                url:"add/members",
                method:"GET",
                params:{
                    ...this.vipForm,
                    storeId:this.storeId
                }
            }).then(res=>{
                setTimeout(()=>{
                    this.canClick = true;
                },1000);
                this.isqrcode = false;
                this.blurBtn = false;
                this.$message({
                    message: res.data,
                    customClass: 'success'
                });
            }).catch(err=>{
                setTimeout(()=>{
                    this.canClick = true;
                },1000);
            })
        },
        getCode(){
            if(!String(this.vipForm.mobile).trim()){
                this.$message({
                    message: '请输入手机号',
                    customClass: 'error'
                });
                return;
            }
            if (this.codeInfo != "获取验证码") {
                return;
            }
            this.$http
                .post(`${API_BASE_URL}v1/verify-code?mobile=${this.vipForm.mobile}&type=ACCOUNT`)
                .then((res) => {
                    clearInterval(this.timer);
                    let time = 60;
                    this.timer = setInterval(() => {
                        time--;
                        this.codeInfo = `${time}s`;
                        if (time <= 0) {
                            this.codeInfo = "获取验证码";
                            clearInterval(this.timer);
                        }
                    }, 1000);
            });
        },
        // 
        chargePay(){
           let _this = this;
            this.canDeletepayment = false;
            wx.scanQRCode({
                needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType: ["qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success: function (res) {
                    var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    var resultArr = result.split(",");
                    // 支付
                    _this.payCode = resultArr[resultArr.length-1];
                    if(result === 'scan resultStr is here'||_this.payCode === ''||result===''){
                        _this.$message({
                            message: '支付失败，请重新扫描。',
                            customClass: 'error'
                        })
                        return;
                    }
                    let data = {
                        "orderId": _this.curVipChargeInfo.id,
                        "channel": "PAYCARD",
                        "amount": _this.curVipChargeInfo.amount,
                        "authCode": _this.payCode,
                        "notes": "会员充值"
                    }
                    
                    _this.$http.put(API_BASE_URL+'v1/clerk/scanPayments/' + _this.$uuid(), data).then((res)=>{
                        _this.payCode = '';
                        if ( res.status === 202 ) {
                            let overTimeNum = 0;
                            let curOrderId = _this.curVipChargeInfo.id;

                            // _this.delPaymentLodingTimer();
                            _this.payLoadTimer = setInterval(()=>{
                                overTimeNum += 2;
                                if ( overTimeNum >= 180 ) { // 超过180秒，取消订单
                                    clearInterval(_this.payLoadTimer);
                                    // _this.createOrder();
                                    return;
                                }
                                // let that = _this;
                                _this.payLoad(curOrderId, function () {
                                    clearInterval(_this.payLoadTimer);

                                    // _this.createOrder();
                                    _this.showPayLoding = false;
                                    // _this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
                                    _this.$message({
                                        message: '充值成功',
                                        customClass: 'success'
                                    });
                                    // _this.getMemberData(_this.vipData.memberId);
                                    _this.showChargeType = false;
                                    _this.showRecharge = false;
                                    _this.inputVipMoney = "";
                                });
                            }, 2000)
                        } else {
                            
                            // _this.$router.push({path:'/buySuccess/'+sendOrderId});//跳转购买成功页面
                            _this.$message({
                                message: '充值成功',
                                customClass: 'success'
                            });
                            // _this.getMemberData(_this.vipData.memberId);
                            _this.showChargeType = false;
                            _this.showRecharge = false;
                            _this.inputVipMoney = "";
                            // _this.createOrder();
                        
                        }
                    }).catch((err)=>{
                        _this.payCode = '';
                        // _this.showPayLoding = false;
                        if ( err.response.status === 400 ) {
                            // _this.showPayBox = true;
                        }
                    })
                    // 支付结束
                }
            });
        },
        // 等待支付轮训接口
        payLoad: function ( orderId, fn ) {
            this.$http.get(API_BASE_URL+'v1/pay/micropay/query?orderId='+orderId).then((res)=>{
                if ( res.status === 200 ) {
                    fn();
                }else if(res.status === 400 || res.status === 500){
                    // this.showPayBox = true;
                    // this.payApiBtn = true;
                    // this.paymentBtn = true;
                    // this.showPayLoding = false;
                    clearInterval(this.payLoadTimer);
                }
            }).catch(( err )=>{
                // this.showPayBox = true;
                // this.payApiBtn = true;
                // this.paymentBtn = true;
                // this.showPayLoding = false;
                clearInterval(this.payLoadTimer);
            })
        },
        chargeVip(item){
            console.log(this.inputVipMoney)

            if(item){
                this.inputVipMoney = "";
            }else{
                if(!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(this.inputVipMoney)|| this.inputVipMoney == 0){
                    this.$message({
                        message: '充值金额输入有误',
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
                let rechargeLimit = JSON.parse(localStorage.getItem("rechargeLimit"));
                if(Number(this.inputVipMoney)<Number(rechargeLimit)){
                    this.$message({
                        message: '充值金额不能小于'+Number(rechargeLimit)+'元',
                        showClose: true,
                        customClass: 'error'
                    });
                    return;
                }
            }
            this.$http({
                url:API_BASE_URL+"v1/clerk/member-charges/"+this.$uuid(),
                method:"PUT",
                data:{
                    "storeId": this.storeId,
                    "memberId": this.vipData.memberId,
                    "amount": parseFloat(this.inputVipMoney?this.inputVipMoney:item.depositAmount),
                    "chargeRuleId": this.inputVipMoney?'':item.id,
                    "type":"CLERK"
                }
            }).then(res=>{
                this.curVipChargeInfo = res.data;
                this.showChargeType = true;
                console.log(res);
            })
        },
        // 获取充值规则
        getChargeRules(){
            let storeId = localStorage.getItem('storeId');
            this.$http({
                url:API_BASE_URL+"v1/pos/charge-rules",
                method:"GET",
                params:{
                    storeId
                }
            }).then(res=>{
                this.chargeRules = res.data;
            });
        },
        // 选择会员
        selPhoneVip: function ( vipItem ) {
            this.vipData = vipItem;
            this.showVipInp = false;
            this.EnterPhone = "";
            setTimeout(()=>{
                this.showRecharge=true;
            },200);
        },
        // 获取会员数据
        showVipInpFun(){
            this.isqrcode=false;
            this.blurBtn=false;
            setTimeout(()=>{
                this.showVipInp=true;
            },500);
        },
        getQrcode(){
            m$.template({
                time:'',
                val:''
            });
            this.$http.get('/referral-code?storeId='+localStorage.getItem('storeId')).then((res)=>{
                m$.template({
                    time:0,
                    val:''
                })
                this.isqrcode = true;
                this.blurBtn  = true;
                setTimeout(()=>{
                    let qrcode = new QRCode("qrcode", {
                        text:  res.data,
                        colorDark : "#000000",
                        colorLight : "#ffffff",
                        correctLevel : QRCode.CorrectLevel.H
                    });
                },200);

                this.$http.get('/stores/'+this.storeId).then((res)=>{
                    localStorage.setItem("rechargeLimit",JSON.stringify(res.data.rechargeLimit));
                });


            }).catch((res)=>{
               m$.template({
                    time:0,
                    val:''
                })  
            })
        },
        logout: function () {
            this.$http.post(API_BASE_URL+'logout', {}).then((res)=>{
                    localStorage.clear();
                    sessionStorage.clear();
                    this.$router.push({path:'/login'});
                }).catch((err)=>{

                })
        },
        getPar() {
            this.$http({
                url: "region/list",
                method: "POST",
                data: {
                    storeId: this.storeId,
                },
            }).then((res) => {
                this.showRegion = false;
                if (res.data && Array.isArray(res.data) && res.data.length) {
                    this.showRegion = true;
                    // res.data.forEach((it) => {
                    //     if (it.nums && Array.isArray(it.nums) && it.nums.length) {
                    //         this.showRegion = true;
                    //     }
                    // });
                }
            })
        },
        getSoreInfo(storeId){
            this.$http.get('/stores/'+storeId).then((res)=>{
                if(res.data.makeEnabled && new Date(res.data.makeEndTime).getTime() > new Date().getTime()){
                    this.makeEnabled = 1;
                }else{
                    this.makeEnabled = -1;
                }
                if(res.data.leaseProductEnabled){
                    localStorage.setItem("leaseProductEnabled",JSON.stringify(res.data.leaseProductEnabled));
                    try {
                        if(res.data.leaseEndDate){
                            if(new Date().getTime()>new Date(res.data.leaseEndDate).getTime()){
                                localStorage.setItem("leaseProductEnabled","false");
                            }else{
                                localStorage.setItem("leaseProductEnabled",JSON.stringify(res.data.leaseProductEnabled));
                            }
                        }
                    } catch (error) {
                        
                    }
                }else{
                    localStorage.setItem("leaseProductEnabled","false");
                }
            })
        },

    },
    created: function () {
        try {
            let leaseEnabled = localStorage.getItem("leaseEnabled");
            if(leaseEnabled == "true"){
                this.leaseEnabled = true;
            }
        } catch (error) {
            
        }
        if(localStorage.getItem('curVipPerson')){
            //有会员就展示出来
            localStorage.removeItem("curVipPerson");
        }
        if ( !localStorage.getItem('storeId') ) {
            this.$router.push({path:'/login'});
        } else {
            this.storeId = localStorage.getItem('storeId');
            this.getSoreInfo(this.storeId);
            this.$http.post('authorize?storeId='+this.storeId, {}).then((res)=>{
                this.$http.get('/today?storeId='+this.storeId).then((res)=>{
                    this.orderCount = res.data.orderCount;
                }).catch((err)=>{
                    if(err.response.status == 400){
                        this.$router.push({path:'/login'});
                        localStorage.clear();
                        return;
                    }
                });
            }).catch(()=>{
                this.$router.push({path:'/login'});
                localStorage.clear();
            })
            // this.$http.get('/today?storeId='+this.storeId).then((res)=>{
            //     this.orderCount = res.data.orderCount;
            // });
            this.getChargeRules();
            this.getPar();
        }
    },
  	mounted(){
  		m$.setTitle('首页'); 
        $(document).ready(()=>{
            $('.index').height($(window).height());
        });
        try {
          const storeList = JSON.parse(localStorage.getItem("storeList"));
          if(storeList && Array.isArray(storeList) && storeList.length>1){
            this.showSelStore = true;
          }
        } catch (error) {
            
        }
  	}
}
</script>
<style lang="scss" scoped>
	@import "index";
    .more-menu-mask{
        position: fixed;
        top:0;
        left:0;
        right:0;
        bottom:0;
        z-index:9;
        background-color: rgba(0,0,0,.59);
        display: flex;
        justify-content: center;
        align-items: center;
        .more-menu-wrap{
            display: flex;
            width: 5.9rem;
            /* height: 5.9rem; */
            border-radius: .259rem;
            background-color: #fff;
            box-sizing: border-box;
            padding: .3rem .159rem;
            flex-wrap: wrap;
            .more-menu-item{
                width: 33%;
                min-height: 1rem;
                margin-top: .3rem;
                display: flex;
                justify-content: center;
                .menu-inner-wrap{
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    width: 1.3rem;
                    height: 1.3rem;
                    border-radius: .259rem;
                    background-color: #e6944d;
                    .menu-icon{
                        text-align: center;
                        font-size: .59rem;
                        color:#fff;
                    }
                    .menu-name{
                        width: 100%;
                        font-size: .24rem;
                        text-align: center;
                        padding-top: .1rem;
                        color:#fff;
                    }
                }
            }
        }
    }
</style>
